package com.le.tester.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/12/24 10:07
 * description：限制接口请求的次数
 */
@Component
public class RequestLimitUtil {


    @Resource
    private RedisUtil redisUtil;

    //n毫秒内请求次数限制
    public boolean requestLimit(Long maxCount, Long millSecond, HttpServletRequest request) {
        if (null == maxCount) {
            //default value is 5
            maxCount = 2L;
        }
        if (null == millSecond) {
            //default value is 60000
            millSecond = 600L;
        }
        try {
            //redis key
            String key = IPUtil.getIpAddress(request) + ":" + request.getContextPath() + ":" + request.getServletPath();
            Integer currentCount = (Integer) redisUtil.get(key);
            if (null == currentCount) {
                //第一次请求
                redisUtil.setForTimeCustom(key, 1, millSecond, TimeUnit.MILLISECONDS);
                //返回false，标识不限制
                return false;
            }
            if (currentCount > maxCount) {
                //限制
                return true;
            } else {
                redisUtil.incr(key, 1L);
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
